16. Exercise: Add LiveData to GameViewModel
L5 22 Add Your First LiveData SC
Now it’s your turn to complete this exercise yourself.
In this exercise you'll add your first LiveData.
1. Wrap word and score in MutableLiveData:
In GameViewModel, set up word and score as MutableLiveData. word should be a String and score should be a integer.
For example:
val score = MutableLiveData<Int>()
2. Change references to score and word to score.value and word.value and add the required null safety checks:
Check the onSkip() and onCorrect() methods and change references. Add null safety checks, then call the minus and plus functions, respectively. For example:
fun onSkip() {
score.value = (score.value)?.minus(1)
nextWord()
}
3. Initialize score.value to 0.
4. Set up the observation relationship for the score and word LiveDatas:
Move over to GameFragment. UI controllers are where you'll set up the observation relationship. Get the LiveData from your view model and call the observe method. Make sure to pass in this and then an observer lambda. Here's the code to set up an observation relationship for score. This should be in GameFragment.onCreate:
viewModel.score.observe(this, Observer { newScore ->
})
5. Move UI update code to your observers and delete unnecessary code:
You can now move the code to update the score TextView and the word TextView to your Observers. For example, your completed observer for score LiveData should look like this:
viewModel.score.observe(this, Observer { newScore ->
binding.scoreText.text = newScore.toString()
})
Once you've done this, you can delete updateWordText and updateScoreText and any references to them - you shouldn't need them!
6. Add a null safety check when passing currentScore in the gameFinished method:
viewModel.score.value can possibly be null, so add a null safety check in the gameFinished method:
val currentScore = viewModel.score.value ?: 0
As always, run your code. If you set up the observation relationships correctly, it should compile and work exactly the same. By using LiveData, your code is less error prone, because you are ensured that whenever the score or word changes, the UI will update to match.
If you want to start at this step, you can download this exercise code from: Step.03-Exercise-Add-LiveData-to-GameViewModel.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here Step.03-Solution-Add-LiveData-to-GameViewModel or using this git diff.
Task Description:
Check the steps below as you implement them to complete this exercise.
Task Feedback:
You did it! Congratulations! You can check your solution against the solution we’ve provided here Step.03-Solution-Add-LiveData-to-GameViewModel or using this git diff.
Reference documentation